package com.wsx.ones.zone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by wangshuaixin on 17/6/7.
 */
@Repository
public class BaseMongoDaoImpl<T> implements BaseMongoDao<T> {

    @Autowired
    protected MongoTemplate mongoTemplate;

    @Override
    public T save(T t) {
        mongoTemplate.save(t);
        return t;
    }

    @Override
    public T save(T t, String collectionName) {
        mongoTemplate.save(t, collectionName);
        return t;
    }

    @Override
    public T findById(String id) {
        return mongoTemplate.findById(id, this.getClz());
    }

    @Override
    public T findById(String id, String collectionName) {
        return mongoTemplate.findById(id, this.getClz(), collectionName);
    }

    @Override
    public List<T> finds(Query query) {
        return mongoTemplate.find(query, this.getClz());
    }

    @Override
    public void remove(T t) {
        mongoTemplate.remove(t);
    }

    @Override
    public void remove(T t, String collectionName) {
        mongoTemplate.remove(t, collectionName);
    }

    @Override
    public void remove(Query query) {
        mongoTemplate.remove(query, this.getClz());
    }

    protected Class<T> getClz() {
        return (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
}
